package org.springframework.sandbox.nettymvcpost.nettymvc;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

public class NettyMessageDecoder extends LengthFieldBasedFrameDecoder {

    //MarshallingDecoder marshallingDecoder;

    public NettyMessageDecoder(int maxFrameLength, int lengthFieldOffset,
                               int lengthFieldLength,int lengthadjustment,int toStrip) throws IOException {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength,lengthadjustment,toStrip);
       // marshallingDecoder = new MarshallingDecoder();
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in)
            throws Exception {
        ByteBuf frame = (ByteBuf) super.decode(ctx, in);
        //如果为空则说明是一个半包消息，直接返回继续有I/O线程读取后续的码流
        if (frame == null) {
            return null;
        }

        NettyMessage message = new NettyMessage();
        NettyHeader header = new NettyHeader();
        //注意在读的过程中，readIndex的指针也在移动
        //header.setCrcCode(frame.readInt());
        header.setLength(frame.readableBytes());
        /*header.setSessionID(frame.readLong());
        header.setType(frame.readByte());
        header.setPriority(frame.readByte());
*/
        /*int size = frame.readInt();
        if (size > 0) {
            Map<String, Object> attch = new HashMap<String, Object>(size);
            int keySize = 0;
            byte[] keyArray = null;
            String key = null;
            for (int i = 0; i < size; i++) {
                keySize = frame.readInt();
                keyArray = new byte[keySize];
                frame.readBytes(keyArray);
                key = new String(keyArray, "UTF-8");
                attch.put(key, marshallingDecoder.decode(frame));
            }
            keyArray = null;
            key = null;
            header.setAttachment(attch);
        }
        if (frame.readableBytes() > 4) {//说明后面还有第二个附件或者是body，需要继续反序列化读出来
            message.setBody(marshallingDecoder.decode(frame));
        }*/
        message.setNettyHeader(header);
        ByteBuf content=(ByteBuf) frame;
        Charset charset=Charset.defaultCharset();
        String input=content.toString(charset);

        RequestFuture requestFuture= JSONObject.parseObject(input, RequestFuture.class);

        //URI uri=new URI("/getUserNameById");
        String[] patharray=requestFuture.getPath().split("\\.");
        String path= patharray[patharray.length-1];
        URI uri=new URI("/"+path+"extPost"+"?userId="+requestFuture.getRequest().toString());

        //NettyMessage nettyMessage=new NettyMessage();
        message.setObjectbody(content);
        byte [] bytesinfo;
        if(content!=null){
            bytesinfo=new byte[content.readableBytes()];
            content.getBytes(0,bytesinfo);
            message.setBytesbody(bytesinfo);
        }
        FullHttpRequest fullHttpRequest=new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,uri.toASCIIString());
        /*fullHttpRequest.content().readBytes(content);
        content.release();*/
        message.setFullHttpRequest(fullHttpRequest);
        //ByteBuf byteBuf= fullHttpRequest.content();

        //channelHandlerContext.write(fullHttpRequest);
        //ctx.fireChannelRead(fullHttpRequest);
        //ctx.fireChannelRead(nettyMessage);
        return message;
    }
}